package com.goodboys.base.webscoket;

import com.goodboys.entity.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.SessionConnectEvent;

import java.security.Principal;
import java.util.List;

/**
 * STOMP监听类
 * 用于session注册 以及key值获取
 */
public class STOMPConnectEventListener  implements ApplicationListener<SessionConnectEvent> {

    @Autowired
    SocketSessionRegistry webAgentSessionRegistry;

    @Override
    public void onApplicationEvent(SessionConnectEvent event) {
        try {
            StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
            //获取webscoket请求头信息，用户验证之类的操作
            String userId = sha.getFirstNativeHeader("id");
            String type = sha.getNativeHeader("type").get(0);
            String tag = sha.getNativeHeader("tag").get(0);
            String range = sha.getNativeHeader("range").get(0);
            String lng = sha.getNativeHeader("lng").get(0);
            String lat = sha.getNativeHeader("lat").get(0);
            String keyword = sha.getFirstNativeHeader("keyword");
            User user = new User();
            user.setId(userId);
            user.setType((StringUtils.isEmpty(type))?0:Integer.parseInt(type));
            user.setTag((StringUtils.isEmpty(tag))?null:Integer.parseInt(tag));
            user.setRange((StringUtils.isEmpty(range)?100:Integer.parseInt(range)));
            user.setLng(Double.parseDouble(lng));
            user.setLat(Double.parseDouble(lat));
            user.setKeyword(StringUtils.isEmpty(keyword) ? null : keyword);
            user.setSessionId(sha.getSessionId());
            webAgentSessionRegistry.registerSessionId(userId,user);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
}
